import React, { memo, useState } from 'react'

import Taro from '@tarojs/taro'

import { View, Image } from '@tarojs/components'
import _ from 'lodash'

import './index.scss'
import logo from '../../assets/images/logo.png'

import list, { group, groupItem } from './list'

// #region 书写注意
//
// 目前 typescript 版本还无法在装饰器模式下将 Props 注入到 Taro.Component 中的 props 属性
// 需要显示声明 connect 的参数类型并通过 interface 的方式指定 Taro.Component 子类的 props
// 这样才能完成类型检查和 IDE 的自动提示
// 使用函数模式则无此限制
// ref: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/20796
//
// #endregion

type PageStateProps = {
  counter: {
    num: number
  }
}

type PageDispatchProps = {}

type PageOwnProps = {}

type PageState = {}

type IProps = PageStateProps & PageDispatchProps & PageOwnProps & PageState

interface Index {
  props: IProps
}

const Index: React.FC<IProps> = memo(() => {
  const [searchKey, setSearchKey] = useState<string>('')
  const filterList: () => group[] = () => {
    if (_.isEmpty(searchKey)) {
      return list
    }
    const newList: group[] = []
    list.forEach((i) => {
      const newSubList: groupItem[] = []
      i.list.forEach((iSub) => {
        if (!iSub.title.toLocaleLowerCase().includes(searchKey)) {
          return
        }
        newSubList.push(iSub)
      })
      if (newSubList.length > 0) {
        newList.push({ ...i, list: newSubList })
      }
    })
    return newList
  }
  return (
    <View className='demo-home'>
      <View className='demo-home__title'>
        <Image mode='aspectFit' className='demo-home__image' src={logo} />
        <View className='demo-home__text'>Taro3 + Vant</View>
      </View>
      {filterList().map((i) => {
        return (
          <View key={i.groupName}>
            <View className='demo-home-nav'>
              <View className='demo-home-nav__title'>{i.groupName}</View>
              <View className='demo-home-nav__group'>
                {i.list.map((j) => {
                  return (
                    <View
                      key={j.title}
                      className='demo-home-nav__block'
                      data-url='/pages{{ item.path }}/index'
                      onClick={() => {
                        Taro.navigateTo({
                          url: `/pages${j.path}/index`,
                        })
                      }}
                    >
                      {j.title}
                      <van-icon
                        name='arrow'
                        custom-className='demo-home-nav__icon'
                      />
                    </View>
                  )
                })}
              </View>
            </View>
          </View>
        )
      })}
    </View>
  )
})

export default Index
